// pages/vote/list/list.js
const voteApi = require('../../../api/vote.js')
const util = require('../../../utils/util.js')

Page({
  data: {
    activityId: null,
    viewOnly: false,
    candidates: [],
    selectedCandidates: [],
    maxVotes: 1,
    submitting: false
  },

  onLoad(options) {
    if (options.activityId) {
      this.setData({ 
        activityId: options.activityId,
        viewOnly: options.viewOnly === 'true'
      })
      this.loadCandidates()
    }
  },

  // 加载候选人列表
  async loadCandidates() {
    try {
      const res = await voteApi.getCandidateList(this.data.activityId, {
        sort_by: this.data.viewOnly ? 'vote_count' : 'created_at'
      })
      
      if (res.code === 200) {
        const candidates = res.data.items.map(item => ({
          ...item,
          selected: false
        }))
        
        this.setData({
          candidates: candidates,
          maxVotes: res.data.max_votes_per_user || 1
        })
      }
    } catch (error) {
      console.error('加载候选人列表失败:', error)
      util.showError('加载失败')
    }
  },

  // 切换候选人选择
  toggleCandidate(e) {
    if (this.data.viewOnly) return
    
    const id = e.currentTarget.dataset.id
    const candidates = this.data.candidates
    const candidate = candidates.find(c => c.id === id)
    
    if (!candidate) return
    
    // 如果已选中，取消选中
    if (candidate.selected) {
      candidate.selected = false
      const selectedCandidates = this.data.selectedCandidates.filter(cid => cid !== id)
      this.setData({
        candidates: candidates,
        selectedCandidates: selectedCandidates
      })
      return
    }
    
    // 检查是否达到最大加油数
    if (this.data.selectedCandidates.length >= this.data.maxVotes) {
      util.showError(`最多只能选择 ${this.data.maxVotes} 人`)
      return
    }
    
    // 选中
    candidate.selected = true
    this.setData({
      candidates: candidates,
      selectedCandidates: [...this.data.selectedCandidates, id]
    })
  },

  // 清空选择
  clearSelection() {
    const candidates = this.data.candidates.map(c => ({
      ...c,
      selected: false
    }))
    
    this.setData({
      candidates: candidates,
      selectedCandidates: []
    })
  },

  // 预览文件
  previewFile(e) {
    const url = e.currentTarget.dataset.url
    // 这里可以下载文件或打开预览
    wx.downloadFile({
      url: url,
      success: (res) => {
        const filePath = res.tempFilePath
        wx.openDocument({
          filePath: filePath,
          success: () => {
            console.log('打开文档成功')
          },
          fail: (err) => {
            console.error('打开文档失败:', err)
            util.showError('无法打开该文件')
          }
        })
      },
      fail: (err) => {
        console.error('下载文件失败:', err)
        util.showError('下载失败')
      }
    })
  },

  // 提交加油
  async submitVote() {
    if (this.data.selectedCandidates.length === 0) {
      util.showError('请至少选择一位候选人')
      return
    }
    
    if (this.data.submitting) return
    
    // 确认提示
    try {
      await util.confirm(
        `您选择了 ${this.data.selectedCandidates.length} 位候选人，确认加油后不可修改，是否确认？`,
        '确认加油'
      )
    } catch (error) {
      return
    }
    
    this.setData({ submitting: true })
    
    try {
      const res = await voteApi.submitVote(
        this.data.activityId, 
        this.data.selectedCandidates
      )
      
      if (res.code === 200) {
        util.showSuccess('加油成功')
        
        setTimeout(() => {
          wx.navigateBack()
        }, 1500)
      } else {
        util.showError(res.message || '加油失败')
      }
    } catch (error) {
      console.error('提交加油失败:', error)
      util.showError('加油失败，请重试')
    } finally {
      this.setData({ submitting: false })
    }
  },

  // 导出结果
  async exportResults() {
    try {
      util.showSuccess('正在生成导出文件...')
      
      const res = await voteApi.exportVotes(this.data.activityId)
      
      if (res.code === 200) {
        // 下载文件
        wx.downloadFile({
          url: res.data.url,
          success: (downloadRes) => {
            const filePath = downloadRes.tempFilePath
            wx.openDocument({
              filePath: filePath,
              showMenu: true
            })
          }
        })
      }
    } catch (error) {
      console.error('导出失败:', error)
      util.showError('导出失败')
    }
  }
})

